package com.campus.client.controller;

import cn.hutool.core.util.StrUtil;
import com.campus.component.XfXhStreamClient;
import com.campus.config.XfXhConfig;
import com.campus.listener.XfXhWebSocketListener;
import com.campus.pojos.domain.dto.MsgDTO;
import com.campus.result.Result;
import com.campus.utils.AIPictureUtil;
import com.campus.utils.AliOssUtil;
import com.campus.utils.AuthUrlUtill;
import lombok.extern.slf4j.Slf4j;
import okhttp3.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.Collections;
import java.util.UUID;


@RestController
@RequestMapping("/client/ai")
@Slf4j
public class AIController {

    @Autowired
    private XfXhStreamClient xfXhStreamClient;

    @Autowired
    private XfXhConfig xfXhConfig;

    @Autowired
    private AliOssUtil aliOssUtil;


    /**
     * 发送问题
     *
     * @param question 问题
     * @return 星火大模型的回答
     */
    @GetMapping("/sendQuestion")
    public Result sendQuestion(@RequestParam("question") String question) {
        log.info("用户询问问题：{}",question);
        // 如果是无效字符串，则不对大模型进行请求
        if (StrUtil.isBlank(question)) {
            return Result.error("无效问题，请重新输入");
        }
        // 获取连接令牌
        if (!xfXhStreamClient.operateToken(XfXhStreamClient.GET_TOKEN_STATUS)) {
            return Result.error("当前大模型连接数过多，请稍后再试");
        }

        // 创建消息对象
        MsgDTO msgDTO = MsgDTO.createUserMsg(question);
        // 创建监听器
        XfXhWebSocketListener listener = new XfXhWebSocketListener();
        // 发送问题给大模型，生成 websocket 连接
        WebSocket webSocket = xfXhStreamClient.sendMsg(UUID.randomUUID().toString().substring(0, 10), Collections.singletonList(msgDTO), listener);
        if (webSocket == null) {
            // 归还令牌
            xfXhStreamClient.operateToken(XfXhStreamClient.BACK_TOKEN_STATUS);
            return Result.error("系统内部错误，请联系管理员");
        }
        try {
            int count = 0;
            // 为了避免死循环，设置循环次数来定义超时时长
            int maxCount = xfXhConfig.getMaxResponseTime() * 5;
            while (count <= maxCount) {
                Thread.sleep(200);
                if (listener.isWsCloseFlag()) {
                    break;
                }
                count++;
            }
            if (count > maxCount) {
                return Result.error("大模型响应超时，请联系管理员");
            }
            // 响应大模型的答案
            String answer = listener.getAnswer().toString();
            log.info("AI回答：{}",answer);
            return Result.success(answer);
        } catch (InterruptedException e) {
            log.error("错误：" + e.getMessage());
            return Result.error("系统内部错误，请联系管理员");
        } finally {
            // 关闭 websocket 连接
            webSocket.close(1000, "");
            // 归还令牌
            xfXhStreamClient.operateToken(XfXhStreamClient.BACK_TOKEN_STATUS);
        }
    }


    @GetMapping("/sendRequest")
    public Result sendRequest(@RequestParam("imageRequest") String request) throws Exception {
        log.info("用户提出图片需求:{}",request);
        String ApiUrl = "https://spark-api.cn-huabei-1.xf-yun.com/v2.1/tti";
        String authUrl = AuthUrlUtill.getAuthUrl(ApiUrl, xfXhConfig.getApiKey(), xfXhConfig.getApiSecret());
        // URL地址正确
        String json = "{\n" +
                "  \"header\": {\n" +
                "    \"app_id\": \"" + xfXhConfig.getAppId() + "\",\n" +
                "    \"uid\": \"" + UUID.randomUUID().toString().substring(0, 15) + "\"\n" +
                "  },\n" +
                "  \"parameter\": {\n" +
                "    \"chat\": {\n" +
                "      \"domain\": \"tti\",\n" +
                "      \"temperature\": 0.5,\n" +
                "      \"max_tokens\": 4096,\n" +
                "      \"width\": 512,\n" +
                "      \"height\": 512\n" +
                "    }\n" +
                "  },\n" +
                "  \"payload\": {\n" +
                "    \"message\": {\n" +
                "      \"text\": [\n" +
                "        {\n" +
                "          \"role\": \"user\",\n" +
                "          \"content\": \""+ request +"\"\n" +
                "        }\n" +
                "      ]\n" +
                "    }\n" +
                "  }\n" +
                "}";
        String content = AIPictureUtil.doPostJson(authUrl, null, json);

        // 解码Base64字符串
        byte[] imageBytes = Base64.getDecoder().decode(content);

        // 将字节数组转换为图像
        ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
        BufferedImage image = ImageIO.read(bais);

        if (image == null){
            return Result.error("您输入的要求可能不符合规范，请重新输入");
        }
        // 保存图像文件
        UUID uuid = UUID.randomUUID();
        String uuidString = uuid.toString();
        String url = aliOssUtil.upload(imageBytes, uuidString + ".png");
        return Result.success(url);

    }
}
